<?php
namespace App\Common;


use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class ImageUploadCommon {
    //定义一个允许的后缀名属性
    protected $allowExt = ['jpg', 'jpeg', 'png', 'gif'];

    public function save($file, $folder, $file_prefix, $max_width) {
        //进行后缀名的验证,如果没有那么就默认为png
        $extension = strtolower($file->getClientOriginalExtension()) ?? 'png';
        if(! in_array($extension, $this->allowExt)) {
            return false;
        }

        //定义存储路径，文件夹切割能让查找效率更高
        $folder_name =  "uploads/" . $folder.date("Ymd", time());
        $upload_path = public_path() . '/' . $folder_name;

        //定义文件名
        $file_name = $file_prefix . "_" . time() . "_" . str_random(10).".". $extension;

        //将图片移动到目标储存位置
        $file->move($upload_path, $file_name);

        //如果限制了图片宽度，就进行裁剪
        if ($max_width && $extension != 'gif') {
            // 此类封装的函数， 用于裁剪图片
            $this->reduceSize($upload_path . "/" . $file_name);
        }

        //返回图片已经存储的路径
        return ['code' => 200, 'data' => ['path' => config('app_url') . "$folder_name/$file_name"]];
    }

    public function reduceSize($file_name, $max_width) {
        //先实例化，参数是图片物理路径
        $image = Image::make($file_name);
        //将图片的大小进行调整
        $image->resize($max_width, null, function($constraint) {

            //设定宽度 $max_width, 高度等比例双方缩放
            $constraint->aspectRatio();

            //防止裁图时图片尺寸变大
            $constraint->upsize();
        });

        //对图片进行保存
        $image->save();
    }

    public function upload(Request $request, ImageUploadHandle $upload, User $user) {
        //获取所有表单信息并赋值给 $data
        $data = $request->all();

        //如果上传了图片
        if ($request->avatar) {
            //调用上传图片类里的save方法，获取存储的图片路径
            $image = $upload->save($request->avatar, 'avatars', $user->id, 362);

            //将图片路径赋值 $data 里
            $data['avatar'] = $image['path'];
        }
        //更新操作
        $user->update($data);

        //跳转
        return redirect()->route('users.show', $user->id)->with('success','个人资料更新成功！');

    }

}
